package com.anysoft.utils;

import android.content.Context;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anysoft.R;


/**
 * Created by lty on 2017/12/22.
 */

public class TipPopwindowHelper {

    private PopupWindow mPopWin;
    private Context mContext;
    private TextView tv_pop_tips;
    private ImageView iv_down_arrow;

    private static TipPopwindowHelper instance;

    public TipPopwindowHelper(Context context) {
        this.mContext = context;
    }

    public static TipPopwindowHelper getInstance(Context context) {
        if (instance == null) {
            instance = new TipPopwindowHelper(context);
        }
        return instance;
    }

    public void initPopwindow() {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_tax_tips_layout, null);
        mPopWin = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tv_pop_tips = (TextView) contentView.findViewById(R.id.tv_pop_tips);
        iv_down_arrow = (ImageView) contentView.findViewById(R.id.iv_down_arrow);
        mPopWin.setBackgroundDrawable(new BitmapDrawable());    //设置背景，否则setOutsideTouchable无效
        mPopWin.setOutsideTouchable(true);                        //设置点击PopupWindow以外的地方关闭PopupWindow
        mPopWin.setFocusable(true);
    }

    public void setTextContent(String desc) {
        if (tv_pop_tips != null) {
            tv_pop_tips.setText(desc);
        }
    }

    public void showPopLocation(View anchorView) {
        int[] pointPos = new int[2];
        anchorView.getLocationOnScreen(pointPos); //圆点的坐标
        //圆圈的宽度
        int anchorWidth = anchorView.getWidth();
        int anchorHeight = anchorView.getHeight();
        //popwindow的高
        mPopWin.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
//        int popWidth = mPopWin.getContentView().getMeasuredWidth();
        int popHeight = mPopWin.getContentView().getMeasuredHeight();
        //获取屏幕的宽度
        Point screenSize = DisplayUtil.getScreenSize(mContext);

        int xoff = (screenSize.x - DisplayUtil.dp2px(mContext, 200)) / 2;

        //动态设置箭头的位置 , 最后减去的5dp是布局中textview的padding值
        int arrowLeftMargin = pointPos[0] - xoff + anchorWidth / 2 - iv_down_arrow.getWidth() / 2 - DisplayUtil.dp2px(mContext, 5);
        RelativeLayout.LayoutParams downArrowParams = (RelativeLayout.LayoutParams) iv_down_arrow.getLayoutParams();
        downArrowParams.leftMargin = arrowLeftMargin;

        mPopWin.showAtLocation(anchorView, Gravity.NO_GRAVITY, xoff, pointPos[1] - popHeight - 10);
    }
}
